package com.yeren.weixin.gzh.weixin.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yeren.weixin.gzh.weixin.dto.SNSUserInfoDTO;
import com.yeren.weixin.gzh.weixin.dto.WeixinOauth2TokenDTO;
import com.yeren.weixin.gzh.weixin.operation.GetUserInfoExecute;
import com.yeren.weixin.gzh.weixin.operation.TokenExecute;

/**
 * 授权后的回调请求处理
 * 
 * @author liubiao
 *
 */
public class OAuthServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		// 用户同意授权后，能获取到code
		String code = request.getParameter("code");
		System.out.println("code::::::::::::::::::::::::::::::::::::::::::" + code);
		// 用户同意授权
		if (!"authdeny".equals(code)) {
			// 获取网页授权access_token
			WeixinOauth2TokenDTO weixinOauth2Token = TokenExecute.getOauth2AccessToken("wxf9b54a0426aab166", "8481d5df777deb142eb3a18b2691f95b", code);
			System.out.println("weixinOauth2Token::::::::::::::::::::::::::::::::::::::::::" + weixinOauth2Token);
			
			// 网页授权接口访问凭证
			String accessToken1 = weixinOauth2Token.getAccessToken();
			System.out.println("accessToken::::::::::::::::::::::::::::::::::::::::::" + accessToken1);
			
			// 用户标识
			String openId = weixinOauth2Token.getOpenId();
			System.out.println("openId::::::::::::::::::::::::::::::::::::::::::" + openId);
			
			// 获取用户信息1
			SNSUserInfoDTO snsUserInfoDTO = GetUserInfoExecute.getSNSUserInfo(accessToken1, openId);
			System.out.println("snsUserInfo::::::::::::::::::::::::::::::::::::::::::" + snsUserInfoDTO);
			System.out.println("openID："+snsUserInfoDTO.getOpenId());
			System.out.println("昵称："+snsUserInfoDTO.getNickname());
			System.out.println("性别："+snsUserInfoDTO.getSex());
			System.out.println("城市："+snsUserInfoDTO.getCity());
			System.out.println("省份："+snsUserInfoDTO.getProvince());
			System.out.println("国家："+snsUserInfoDTO.getCountry());
			System.out.println("图像："+snsUserInfoDTO.getHeadImgUrl());
			System.out.println("特权："+snsUserInfoDTO.getPrivilegeList());
			// 设置要传递的参数
			request.setAttribute("snsUserInfoDTO", snsUserInfoDTO);
		}
		// 跳转到index.jsp
		request.getRequestDispatcher("weixinSimpleUserInfoList.jsp").forward(request, response);

	}
}
